import {
  Button,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Radio,
  RadioGroup,
  Select,
  Space,
  TypographyText
} from 'ant-design-vue'
import { id } from 'element-plus/es/locale'
import { defineComponent, nextTick, onActivated, ref } from 'vue'
import { useRouter } from 'vue-router'

import { activityRuleApi, commonApi } from '@/apis'
import { editRule, RuleListItem } from '@/apis/activityRuleTypes'
import {
  type ProTableProps,
  type ProTableRef,
  ProEditor,
  ProEditorProps,
  ProEditorRef,
  ProTable
} from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, optionsToMap } from '@/utils'

export default defineComponent({
  name: 'RuleManage',
  setup() {
    const { showConfirm } = useDialog()
    const statusOptions = [{ label: '积分排行榜', value: 1 }]
    const tableRef = ref({} as ProTableRef)
    const showDialog = ref(false)
    const dialogLoading = ref(false)
    const optionItemCur = ref({} as RuleListItem)
    const groupManageStatusMap = optionsToMap(statusOptions)
    const editorConfig = ref({
      wrapStyle: {
        width: '702px'
      },
      editorStyle: {
        height: '300px'
      },
      editorHtml: '',
      editorVisible: false,
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: commonApi.uploadFileUrl,
            fieldName: 'file',
            customInsert(res: any, insertFn: any) {
              // res 即服务端的返回结果
              const url = res.data
              // 从 res 中找到 url alt href ，然后插图图片
              insertFn(url, '', '')
            },
            maxFileSize: 10 * 1024 * 1024,
            onError(file: File, err: any, res: any) {
              if (file && file.size > 10 * 1024 * 1024) {
                message.error('图片超过10M，请压缩图片或分段上传')
              }
            }
          }
        } as any
      },
      toolbarConfig: {
        excludeKeys: ['group-video']
      }
    } as ProEditorProps)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        // formConfig: {
        //   items: [
        //     {
        //       field: 'labelStatus',
        //       itemRender: {
        //         name: TABLE_ITEM_RENDER.ASelect,
        //         props: {
        //           placeholder: '选择类型',
        //           allowClear: true
        //         },
        //         options: statusOptions
        //       }
        //     },
        //     {
        //       field: 'labelName',
        //       itemRender: {
        //         name: TABLE_ITEM_RENDER.AInput,
        //         props: {
        //           placeholder: '请输入关键词',
        //           allowClear: true
        //         }
        //       }
        //     },
        //     {
        //       itemRender: {
        //         name: TABLE_RENDERER.FormItemBtns
        //       }
        //     }
        //   ]
        // },
        columns: [
          {
            title: '规则名称',
            field: 'ruleTitle'
          },
          {
            title: '规则类型',
            field: 'ruleType',
            formatter: ({ cellValue }) => {
              if (cellValue === 0) {
                return '-'
              }
              return groupManageStatusMap[cellValue]
            }
          },
          {
            title: '添加时间',
            field: 'createTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '修改时间',
            field: 'updateTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 180
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await activityRuleApi.getRuleList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()
    //新增
    function add(item) {
      router.push({
        name: 'AddRule',
        query: {
          id: item ? item.id : null
        }
      })
    }

    //编辑
    function edit(item) {
      Object.assign(optionItemCur.value, item)
      showDialog.value = true
    }
    onActivated(() => {
      tableRef.value.refresh()
    })
    //删除
    function handleDelete(item: RuleListItem) {
      console.log(item.id)
      showConfirm({
        content: `确定删除该规则吗？`,
        onOk: async () => {
          try {
            await activityRuleApi.deleteRule(item.id)
            tableRef.value.refresh()
          } catch {}
        }
      })
    }
    //编辑
    function handleEdit(item: RuleListItem) {
      console.log(item.ruleDetails)
      optionItemCur.value = item
      showDialog.value = true
      editorConfig.value.editorHtml = ''
      if (item.ruleDetails) {
        editorConfig.value.editorHtml = item.ruleDetails
      }
      editRule.value.ruleTitle = item.ruleTitle
      editRule.value.ruleType = item.ruleType
      editRule.value.id = item.id
      editorConfig.value.editorVisible = true
    }
    const editorRef = ref({} as ProEditorRef)
    const editRule = ref({} as editRule)
    //编辑确定
    async function handleConfirm() {
      dialogLoading.value = true
      editRule.value.ruleDetails = editorRef.value.editor.getHtml()
      // if (editItemCur.value.ruleType == 1) {
      //   editorData = editorRef.value.editor.getText()
      // } else {
      //   editorData = editorRef.value.editor.getHtml()
      // }
      try {
        await activityRuleApi.editRule(editRule.value)
        showDialog.value = false
      } finally {
        dialogLoading.value = false
      }
      tableRef.value.refresh()
    }

    return {
      editorRef,
      editRule,
      tableRef,
      tableConfig,
      editorConfig,
      showDialog,
      dialogLoading,
      optionItemCur,
      statusOptions,
      handleConfirm,
      add,
      edit,
      handleDelete,
      handleEdit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>
              </Space>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button type="primary" onClick={this.add}>
                    添加规则
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
        <Modal
          confirmLoading={this.dialogLoading}
          v-model:visible={this.showDialog}
          width={1000}
          title={'编辑'}
          destroyOnClose
          onOk={this.handleConfirm}
        >
          <Form style={{ marginTop: '15px' }}>
            <FormItem label={'规则标题'} required>
              <Input
                placeholder={'请输入'}
                v-model:value={this.editRule.ruleTitle}
                style={{ width: '200px' }}
              />
            </FormItem>
            <FormItem label={'规则类型'} required>
              <Select
                v-model:value={this.editRule.ruleType}
                placeholder="请选择"
                style={{ width: '200px' }}
                options={this.statusOptions}
              ></Select>
            </FormItem>
          </Form>
          <ProEditor ref="editorRef" {...this.editorConfig} />
        </Modal>
      </div>
    )
  }
})
